<?php
class DbConfigService
{
	//数据库域名
	private $host;
	//数据库名字
	private $dbName;
	//数据库用户名
	private $dbUname;
	//数据库密码
	private $dbPword;
	//表名前缀
	private $dbPrefix;
	//初始用户名
	private $username;
	//初始密码
	private $password;

	/**
	 * 检测数据库是否连接成功
	 * @Author   Leikes
	 * @DateTime 2016-01-08T10:14:15+0800
	 * @return   array                   errCode,message
	 */
	public function checkConfig()
	{
		try {
			    $conn = new PDO("mysql:host=".$this->host.";dbname=".$this->dbName."", $this->dbUname, $this->dbPword);
			    return CMSException::$ok; 
		    }
		catch(Exception $e)
		    {
		    	return CMSException::$linkErr;
		    }
	}


	/**
	 * 写入配置文件
	 * @Author   Leikes
	 * @DateTime 2016-01-08T10:16:48+0800
	 * @return   array                   errCode,message
	 */
	public function writeConfig()
	{
		File::put('DBConfig/DBConfig.ini',$this->host."\n".$this->dbName."\n".$this->dbUname."\n".$this->dbPword."\n".$this->dbPrefix."\n");
		$this->createTable();
		$this->addUser();
	}


	/**
	 * 在数据库中建立默认表格
	 * @Author   Leikes
	 * @DateTime 2016-01-08T13:40:27+0800
	 * @return   void
	 */
	private function createTable()
	{
		Schema::create('users', function($table)
		{
			$table->increments('id');
			$table->string('username');
			$table->string('password');
			$table->timestamps(); 
		});

		Schema::create('models', function($table)
		{
			$table->increments('id');
			$table->string('model_name');
			$table->string('table_name');
			$table->timestamps(); 

		});

		Schema::create('categorys',function($table)
		{
			$table->increments('id');
			$table->string('category_name');
			$table->integer('model_id')->unsigned()->index('model_id');
			$table->timestamps(); 

			$table->foreign('model_id')->references('id')->on('models');
		});
		
		Schema::create('fields',function($table)
		{
			$table->increments('id');
			$table->Integer('model_id')->unsigned()->index('column_id');
			$table->string('display_name');
			$table->string('field_name');
			$table->string('field_type');
			$table->timestamps();

			$table->foreign('model_id')->references('id')->on('models');  
		});
	}
	
	/**
	 * 添加初始用户
	 * @Author   Leikes
	 * @DateTime 2016-01-11T10:19:16+0800
	 */
	private function addUser()
	{
		User::create([
			'username'=>$this->username,
			'password'=>$this->password
			]);
	}

	public function setHost($host)
	{
		$this->host=$host;
	}

	public function setDbName($dbName)
	{
		$this->dbName=$dbName;
	}

	public function setDbUname($dbUname)
	{
		$this->dbUname=$dbUname;
	}

	public function setDbPword($dbPword)
	{
		$this->dbPword=$dbPword;
	}

	public function setDbPrefix($dbPrefix)
	{
		$this->dbPrefix=$dbPrefix;
	}

	public function setUserName($username)
	{
		$this->username=$username;
	}

	public function setPassWord($password)
	{
		$this->password=Hash::make($password);
	}
}
?>
